package com.erebus.service.impl;

import com.erebus.model.dto.Draft;
import com.erebus.model.dto.User;
import com.erebus.service.YanQiService;
import com.erebus.utils.DivinationAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class YanQiServiceImpl implements YanQiService {
    @Autowired
    private RedisTemplate redisTemplate;

    private DivinationAlgorithm divinationAlgorithm = new DivinationAlgorithm();


    @Override
    public int getBian(String redisKey) {

        User user = (User)redisTemplate.opsForValue().get(redisKey);
        Draft draft = user.getDraft();


        if (draft.getI()== 3 || draft.getI() == 6 || draft.getI() == 9 || draft.getI() == 12 || draft.getI() == 15) { // 二爻 / 三爻
            draft.setSum(49);
        }

        int j, k; // 天地
        int[] list = new int[3];


        // 分天地
        j = dichotomy(draft.getSum());
        k = draft.getSum() - j; // 地
        list[0] = 1; // 人
        k -= 1;

        if (j % 4 == 0) {
            list[1] = 4;
        } else {
            list[1] = j % 4;
        }
        if (k % 4 == 0) {
            list[2] = 4;
        } else {
            list[2] = k % 4;
        }
        int a = Arrays.stream(list).sum();
        int[] bian = draft.getBian();
        bian[draft.getI()] = a;
        draft.setBian(bian);
        draft.setSum(draft.getSum() - a);
        draft.setI(draft.getI() + 1); // 变数+1

        redisTemplate.delete(redisKey);
        redisTemplate.opsForValue().set(redisKey,user);

        return a;
    }

    @Override
    public int getYao(String redisKey) {
        User user = (User)redisTemplate.opsForValue().get(redisKey);
        Draft draft = user.getDraft();
        int y = draft.getSum() / 4;
        int[] yao = draft.getYao();
        yao[draft.getJ()] = y;
        draft.setJ(draft.getJ() + 1);
        draft.setYao(yao);
        redisTemplate.delete(redisKey);
        redisTemplate.opsForValue().set(redisKey,user);
        return y;
    }

    @Override
    public ResponseEntity<byte[]> getImg(String redisKey) throws IOException {
        User user = (User)redisTemplate.opsForValue().get(redisKey);
        Draft draft = user.getDraft();
        String string = divinationAlgorithm.toBinaryString(draft.getYao());
        int index = divinationAlgorithm.parseBinaryStringToInt(string);
        System.out.println(index);

        // 构建图片路径
        String imgUrl = "res/" + index + ".png";
        // 读取图片文件
        byte[] imageBytes = Files.readAllBytes(Paths.get(new ClassPathResource(imgUrl).getURI()));

        // 返回图片
        return ResponseEntity.ok()
                .headers(new HttpHeaders())
                .contentType(MediaType.IMAGE_PNG)
                .body(imageBytes);
    }

    @Override
    public ResponseEntity<byte[]> getImgs(String codeStr) throws IOException {
        // 字符串转列表
        int[] list = new int[6];
        // 分割字符串
        String[] split = codeStr.split(",");
        List<String> temp = Arrays.stream(split).toList();
        for (int i = 0; i< 6; i++){
            list[i] = Integer.parseInt(temp.get(i));
        }

        String string = divinationAlgorithm.toBinaryString(list);
        int index = divinationAlgorithm.parseBinaryStringToInt(string);
        System.out.println(index);

        // 构建图片路径
        String imgUrl = "res/" + index + ".png";
        // 读取图片文件
        byte[] imageBytes = Files.readAllBytes(Paths.get(new ClassPathResource(imgUrl).getURI()));

        // 返回图片
        return ResponseEntity.ok()
                .headers(new HttpHeaders())
                .contentType(MediaType.IMAGE_PNG)
                .body(imageBytes);

    }

    // 二分，返回天数
    private int dichotomy(int i) {
        int j = i / 2;
        int a = j - 10;
        int b = j + 10;
        // 生成a-b随机数
        int c = (int) (Math.random() * (b - a + 1) + a);

        return c;
    }


    @Override
    public String getText(String redisKey) {
        User user = (User)redisTemplate.opsForValue().get(redisKey);
        Draft draft = user.getDraft();
        String string = divinationAlgorithm.toBinaryString(draft.getYao());
        int index = divinationAlgorithm.parseBinaryStringToInt(string);
        String text = divinationAlgorithm.getDivinationResult(index);
        return text;
    }

    @Override
    public String getTexts(String codeStr) {
        int[] list = new int[6];
        // 分割字符串
        String[] split = codeStr.split(",");
        List<String> temp = Arrays.stream(split).toList();
        for (int i = 0; i< 6; i++){
            list[i] = Integer.parseInt(temp.get(i));
        }

        String string = divinationAlgorithm.toBinaryString(list);
        int index = divinationAlgorithm.parseBinaryStringToInt(string);
        String text = divinationAlgorithm.getDivinationResult(index);
        return text;
    }
}
